// pages/recommend/recommend.js
import request from '../../utils/request.js'
import PubSub from 'pubsub-js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
	year: '',
	month: '',
	day: '',
	recommendList: [],
	index: 0, //点击音乐下标
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
	let userInfo = wx.getStorageSync('userInfo')
	if (!userInfo) {
		wx.showToast({
			title: '请先登录！',
			icon:'none',
			success() {
				wx.reLaunch({
					url: '/pages/login/login'
				})
			}
		})
	}
	this.setData({
		year: new Date().getFullYear(),
		month: new Date().getMonth() + 1,
		day: new Date().getDay()
	})
	this.recommendList()
	
	//订阅来自songDetail页面发布的消息
	PubSub.subscribe('switchType',(msg,type) => {
		let {recommendList,index} = this.data
		if (type === 'pre') {
			(index === 0) && (index = recommendList.length)
			index -= 1
		}else {
			(index === recommendList.length - 1) && (index = -1)
			index += 1
		}
		this.setData({
			index
		})
		let musicId = this.data.recommendList[index].id
		//计算完将音乐id传递给详情页
		PubSub.publish('musicId',musicId)
	})
  },
  
  async recommendList() {
	  let res = await request('/recommend/songs')
	  this.setData({
		  recommendList: res.recommend
	  })
  },
  
  toSongDetail(e) {
	// let currentSong = e.currentTarget.dataset.song
	// let index = e.currentTarget.dataset.index
	let {song,index} = e.currentTarget.dataset
	//路由跳转传参
	wx.navigateTo({
		url: '/pages/songDetail/songDetail?musicId=' + song.id
	})
	this.setData({
		index
	})
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})